package com.xskj.web.optServlet;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author : xskj
 * @description: servelt优化写法  这是封装的Servelt基础类
 * @date : 2021/11/30 23:32
 */

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取方法名
        String url = req.getRequestURI();
        int index = url.lastIndexOf("/");
        String method = url.substring(index + 1);

        //获取DemoServlet对象
        Class<? extends  BaseServlet> cls = this.getClass();

        try {
            //获取方法
            Method m = cls.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法       this指DemoServlet
            m.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
